package cn.e4j.modular.api.controller;

import cn.digiwin.wx.utils.WeixinHandler;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.StringUtils;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.FwbgService;
import cn.e4j.modular.api.service.FwpgService;
import cn.e4j.modular.api.upload.ImgUtils;
import cn.e4j.modular.api.util.CommonUtils;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.crm.entity.*;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.service.impl.SystemServiceImpl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *功能描述
 * @author caijy
 * @description 服务报工
 * @datetime 2019-11-8 0008 17:18
 * @return
 */
@RestController
@RequestMapping("api/wx/fwbg")
public class FwbgController extends ControllerSupport {

    private static Logger logger = LoggerFactory.getLogger(FwpgController.class);

    @Autowired
    FwbgService fwbgService;

    @Autowired
    FwpgService fwpgService;

    @Autowired
    SystemServiceImpl systemService;

    /**
     * 获取现场回报列表
     *
     * @return
     */
    @RequestMapping(value = "getList")
    public ResponseData getList(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        SysUser currentUser = wapper.getSysUser();
        try {
            inDto.put("MMRFent", currentUser.getDBC());
            inDto.put("MMRF007", currentUser.getID());//员工编号

            //上下级权限
            Dto sys003 = systemService.getSys003(currentUser);
            inDto.put("ORGS", sys003.get("ORGS"));

            //业务员权限
            Dto sys004 = systemService.getSys004(currentUser,(List<Dto>)sys003.get("ORGS"));
            inDto.put("YWY", sys004.get("YWY"));

            list = fwbgService.getListPage(wapper.getPage(),inDto);
        } catch (Exception e) {
            e.printStackTrace();
           return ERROR;
        }
        return SUCCESS(list);
    }


    @RequestMapping(value = "saveData")
    public ResponseData saveData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        MmrgT mmrgT = new MmrgT();
        MmrdT mmrdT = new MmrdT();
        List<MmrhT> MmrhTs = new ArrayList<>();
        List<MmriT> MmriTs = new ArrayList<>();
        List<MmrqT> mmrqTS = new ArrayList<>();
        ResponseData data = new ResponseData();
        String errmsg = "ok";
        List<Dto> list= new ArrayList<>();
        try {

            JSONObject inJson = JSONObject.parseObject(inDto.getString("obj"));

            //data = ImgUtils.base64ToImg(inJson.getString("signature"));
            if(inJson.getString("signature") != null && (!inJson.getString("signature").equals("")) ) {
                data = ImgUtils.base64ToImg(inJson.getString("signature"));
            }else {
                data.setCode(200);
            }
            if (data.getCode() == 200) {


                inDto.put("MMRFENT", inDto.getString("ENT"));
                inDto.put("MMRF007", currentUser.getID());//员工编号

                mmrgT.setMMRGENT(inDto.getString("ENT"));
                mmrgT.setMMRGDOCNO(inJson.getString("MMRGDOCNO"));
                mmrgT.setMMRGSEQ(BigDecimal.ONE);
                mmrgT.setMMRGDOCDATE(LocalDate.now());
                mmrgT.setMMRG001(inJson.getString("MMRFDOCNO"));
                mmrgT.setMMRG002(inJson.getBigDecimal("MMRFSEQ"));
                mmrgT.setMMRG003(inJson.getString("MMRF003"));
                mmrgT.setMMRG004(inJson.getString("MMRF004"));
                mmrgT.setMMRG005(currentUser.getID());

                Date MMRF009 = inJson.getDate("MMRF009");
                if (MMRF009 != null) {
                    mmrgT.setMMRG006(CommonUtils.dateToLocalDate(MMRF009));
                }else{
                    mmrgT.setMMRG006(LocalDate.now());
                }
                mmrgT.setMMRG007(CommonUtils.dateToLocalDate(inJson.getDate("MMRG007")));
                mmrgT.setMMRG008(inJson.getString("MMRG008"));
                mmrgT.setMMRG009(inJson.getString("MMRG009"));// 图片地址
                mmrgT.setMMRG010(inJson.getString("MMRG010"));
                mmrgT.setMMRG011(inJson.getString("MMRG011"));
                mmrgT.setMMRG012(data.getData()+""); // 签名地址
                mmrgT.setMMRG013(inJson.getString("MMRG013"));// 20200305改成存储设备维修好后的图片
                mmrgT.setMMRG100(inJson.getString("MMRG100"));
                mmrgT.setMMRG101(inJson.getString("MMRG101"));//差旅时数
                mmrgT.setMMRG102(inJson.getString("MMRG102"));
                //mmrgT.setMMRG103(DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss));//签出时间
                mmrgT.setMMRG103(LocalDateTime.now());//签出时间
                mmrgT.setMMRG104(inJson.getBigDecimal("MMRG104"));//报工时数
                mmrgT.setMMRGACTI("Y");
                mmrgT.setMMRGDATE(LocalDate.now());
                mmrgT.setMMRGTIME(DateUtils.getTime());
                mmrgT.setMMRGUSER(currentUser.getID());

                // 修改 mmrd表 状态为4报工
                mmrdT.setMMRDENT(inDto.getString("ENT"));
                mmrdT.setMMRDSEQ(inJson.getBigDecimal("MMRDSEQ"));
                mmrdT.setMMRDDOCNO(inJson.getString("MMRF001"));
                mmrdT.setMMRD020("4");

                JSONArray mmrhJA = inJson.getJSONArray("pjlist");

                GwamT gwam = new GwamT();
                for (int i = 0, j = mmrhJA.size(); i < j; i++) {
                    JSONObject item = mmrhJA.getJSONObject(i);
                    MmrhT mmrh = new MmrhT();
                    mmrh.setMMRHENT(inDto.getString("ENT"));
                    mmrh.setMMRHDOCNO(mmrgT.getMMRGDOCNO());
                    mmrh.setMMRHSEQ(BigDecimal.valueOf(i+1));
                    mmrh.setMMRH001(item.getString("MMRH001"));
                    mmrh.setMMRH002(item.getString("MMRH002"));
                    mmrh.setMMRH003(item.getString("MMRS004"));
                    mmrh.setMMRH004(item.getBigDecimal("MMRH004"));
                    mmrh.setMMRH005(item.getBigDecimal("MMRS009"));
                    mmrh.setMMRH006(item.getString("MMRH002").equals("1") ? mmrh.getMMRH004().multiply(mmrh.getMMRH005()) : BigDecimal.ZERO);

                    gwam = gwam.selectById(item.getString("MMRS004"));
                    if (gwam != null && CommonUtils.isNum(gwam.getGWAM012()) && CommonUtils.isNum(gwam.getGWAM013())) {
                        mmrh.setMMRH007(CommonUtils.addDays(LocalDate.now(),
                                Integer.parseInt(gwam.getGWAM012())*30+Integer.parseInt(gwam.getGWAM013()))); //配件三包到期日期
                    }
                    mmrh.setMMRH008(item.getString("MMRS010"));
                    mmrh.setMMRH009(item.getString("MMRH009"));
                    mmrh.setMMRHACTI("Y");
                    mmrh.setMMRHDATE(LocalDate.now());
                    mmrh.setMMRHTIME(DateUtils.getTime());
                    mmrh.setMMRHUSER(currentUser.getID());
                    MmrhTs.add(mmrh);
                }
                JSONArray expenses = inJson.getJSONArray("expensesList");

                for (int i = 0, j = expenses.size(); i < j; i++) {
                    JSONObject item = expenses.getJSONObject(i);
                    MmriT mmri = new MmriT();
                    mmri.setMMRIENT(inDto.getString("ENT"));
                    mmri.setMMRIDOCNO(mmrgT.getMMRGDOCNO());
                    mmri.setMMRISEQ(BigDecimal.valueOf(i+1));
                    mmri.setMMRI001(item.getString("MMRI001"));
                    mmri.setMMRI002(item.getBigDecimal("MMRI002"));
                    mmri.setMMRI003(item.getBigDecimal("MMRI003"));
                    mmri.setMMRIACTI("Y");
                    mmri.setMMRIDATE(LocalDate.now());
                    mmri.setMMRITIME(DateUtils.getTime());
                    mmri.setMMRIUSER(currentUser.getID());
                    MmriTs.add(mmri);
                }

                //
                String MMRD013s = inJson.getString("MMRD013");
                String[] MMRD013Array = MMRD013s.split(",");

                int seq = 1;
                for(String MMRD013:MMRD013Array){
                    if (StringUtils.isNotEmpty(MMRD013)){
                        MmrqT mmrqT = new MmrqT();
                        mmrqT.setMMRQDOCNO(mmrgT.getMMRGDOCNO());
                        mmrqT.setMMRQENT(inDto.getString("ENT"));
                        mmrqT.setMMRQSEQ(seq);
                        mmrqT.setMMRQ001(MMRD013);

                        mmrqT.setMMRQACTI("Y");
                        mmrqT.setMMRQDATE(LocalDate.now());
                        mmrqT.setMMRQTIME(DateUtils.getTime());
                        mmrqT.setMMRQUSER(currentUser.getID());
                        mmrqT.setMMRQGRUP(currentUser.getORG_ID());
                        mmrqT.setMMRQORIG(currentUser.getORG_ID());
                        mmrqT.setMMRQORIU(currentUser.getID());

                        mmrqTS.add(mmrqT);
                        seq ++;
                    }
                }

                fwbgService.saveData(mmrgT,MmrhTs,MmriTs,mmrdT,mmrqTS);
                Dto msgDto = Dtos.newDto();
                msgDto.put("gwaml003", inJson.getString("GWAML003"));
                Dto mmraDto = Dtos.newDto();
                mmraDto.put("MMRD002", mmrgT.getMMRG003());
                mmraDto.put("MMRD003", mmrgT.getMMRG004());
                Dto mmra = fwpgService.getGwakl004(mmraDto);
                msgDto.put("gwakl004", mmra.getString("GWAKL004"));
                Dto mmrdDto = Dtos.newDto();
                mmrdDto.put("MMRDDOCNO", inJson.getString("MMRF001"));
                mmrdDto.put("MMRDSEQ",inJson.getInteger("MMRDSEQ"));
                Dto mmrd = fwbgService.getMmrdData(mmrdDto);
                if(mmrd != null){
                    msgDto.put("yyuser", mmrd.getString("MMRD017"));
                }else{
                    msgDto.put("yyuser", "");
                }
                list.add(msgDto);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        try {
            if (ToolUtil.isNotEmpty(list)){
                list.forEach(dto->{
                    //品名
                    String gwaml003 = dto.getString("gwaml003");
                    String gwakl004 = dto.getString("gwakl004");
                    String userId = currentUser.getID();
                    if (ToolUtil.isEmpty(gwaml003))
                        logger.error("消息中品名获取为空！");
                    else {
                        //派工人员
                        Dto pgDto = Dtos.newDto();
                        pgDto.put("userid", userId);
                        pgDto.put("GWAAENT", inDto.getString("ENT"));
                        Dto gwaa2 = fwpgService.getGwaa2(pgDto);

                        if (ToolUtil.isEmpty(gwaa2))
                            logger.error("消息中派工人员获取为空！");
                        else {
//                                //派工消息
//                                String pgmsg = String.format("设备[%s]已安排您去维修，请注意！",gwaml003);
//                                WeixinHandler.sendMsg(gwaa2,pgmsg);

                            String gwaa002 = gwaa2.getString("NAME");

                            //预约者
                            String yyuser = dto.getString("yyuser");

                            if (ToolUtil.isEmpty(yyuser))
                                logger.error("消息中预约者获取为空！");
                            else {
                                Dto yyDto = new Dto();
                                yyDto.put("GWAA001",yyuser);
                                yyDto.put("GWAAENT", inDto.getString("ENT"));
                                Dto gwaa21 = fwpgService.getGwaa2(yyDto);

                                if (ToolUtil.isNotEmpty(gwaa21) && gwaa002!=null){
                                    //预约者消息
                                    String msg = String.format("[%s]客户的[%s]设备由[%s]工程师维修完毕！",gwakl004,gwaml003,gwaa002);
                                    WeixinHandler.sendMsg(gwaa21,msg);
                                }
                            }

                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }

    /**
     * 获取产品信息
     *
     * @param wapper
     * @return
     */
    @RequestMapping(value = "getMmraData")
    public ResponseData getMmraData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        Dto mmra = Dtos.newDto();
        try {
            mmra = fwbgService.getMmraData(inDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS(mmra);
    }
    /**
     * 获取历史维修记录列表
     *
     * @param wapper
     * @return
     */
    @RequestMapping(value = "getMmrdList")
    public ResponseData getMmrdList(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        try {
            list = fwbgService.getMmrdListPage(inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }
}
